package yns.springboot.guide.demo.aop;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import yns.springboot.guide.demo.aop.annotation.CommonAnnotation;

@Aspect
@Component
public class CommonAnnotationAspect {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Pointcut("@annotation(yns.springboot.guide.demo.aop.annotation.CommonAnnotation)")
	public void commonAnnotation() {
		logger.info("CommonAnnotationAspect commonAnnotation method");
	}

	@Before("commonAnnotation()")
	public void commonAnnotationBefore(JoinPoint joinPoint) {
		logger.info("目标方法名为 ：" + joinPoint.getSignature().getName());
		logger.info("目标方法所属类的类名 ：" + joinPoint.getSignature().getDeclaringType().getSimpleName());
		logger.info("目标方法所属类的包名（包括类名） ：" + joinPoint.getSignature().getDeclaringTypeName());
		logger.info("目标方法声明类型 ：" + Modifier.toString(joinPoint.getSignature().getModifiers()));
		
		MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
		Method method = methodSignature.getMethod();
		CommonAnnotation commonAnnotation = (CommonAnnotation) method.getAnnotation(CommonAnnotation.class);
		
		logger.info("注解的参数 ：" + commonAnnotation.name());
	}

	@Around("commonAnnotation()")
	public Object Interceptor(ProceedingJoinPoint proceedingJoinPoint) {
		logger.info("CommonAnnotationAspect Interceptor method");

		Object[] args = proceedingJoinPoint.getArgs();
		Class<? extends Object> clazz = proceedingJoinPoint.getTarget().getClass();
		Signature signature = proceedingJoinPoint.getSignature();

		logger.info("CommonAnnotationAspect Interceptor : Args=" + Arrays.asList(args) + ",Method=" + signature
				+ ",TargetClass=" + clazz);

		Object result = null;
		try {
			result = proceedingJoinPoint.proceed();
		} catch (Throwable e) {
			e.printStackTrace();
		}
		return result;
	}
}
